package com.yangyuhao.haowuyoupin;

import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.yangyuhao.haowuyoupin.adapter.ProductAdapter;
import com.yangyuhao.haowuyoupin.model.ProductResponse;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class ProductListActivity extends AppCompatActivity {
    private ProductAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);

        // 设置返回按钮点击事件
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        
        // 添加这段代码，设置底部提示占据整行
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.getItemViewType(position) == ProductAdapter.TYPE_FOOTER ? 2 : 1;
            }
        });
        
        recyclerView.setLayoutManager(layoutManager);

        try {
            InputStream inputStream = getResources().openRawResource(R.raw.products);
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            Gson gson = new Gson();
            ProductResponse response = gson.fromJson(reader, ProductResponse.class);
            
            adapter = new ProductAdapter(this, response.getProducts());
            recyclerView.setAdapter(adapter);
            
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                    int totalItemCount = layoutManager.getItemCount();
                    if (lastVisibleItem >= totalItemCount - 4) {
                        adapter.showFooter(true);
                    }
                }
            }
        });
    }
} 